<template>
  <div class="params-container">
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容区域 -->
    <el-card>
      <!-- 头部提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        show-icon
        :closable="false"
        type="warning"
      >
      </el-alert>
      <!-- 级联下拉菜单 -->
      <el-row class="margin">
        <el-col>
          选择商品分类:
          <el-cascader
            v-model="selectCateKeys"
            :options="CateList"
            :props="cateListProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableList" border stripe>
            <el-table-column type="expand">
              <!-- slot-scope="scope" 可以获取表格当前行的数据 -->
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="henderClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showUpdateForm(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeCate(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableList" border stripe>
            <el-table-column type="expand">
              <!-- slot-scope="scope" 可以获取表格当前行的数据 -->
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="henderClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showUpdateForm(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeCate(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addFormClosed"
    >
      <!-- 添加表单 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数/属性的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="updateDialogVisible"
      width="50%"
      @close="updateFormClosed"
    >
      <!-- 添加表单 -->
      <el-form
        :model="updateForm"
        :rules="updateFormrules"
        ref="updateFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="updateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入getAllCateListAPI接口
import { getAllCateListAPI } from '@/api/getAllCateListAPI.js'
// 导入getCateGoriesAPI接口
import { getCateGoriesAPI } from '@/api/getCateGoriesAPI.js'
// 导入addParamsAPI接口
import { addParamsAPI } from '@/api/addParamsAPI.js'
// 导入 getUpdateCateAPI 接口
import { getUpdateCateAPI } from '@/api/getUpdateCateAPI.js'
// 导入 updateParamsAPI接口
import { updateParamsAPI } from '@/api/updateParamAPI.js'
// 导入removeCateAPI接口
import { removeCateAPI } from '@/api/removeCateAPI.js'
// 导入submitParamsAPI接口
import { submitParamsAPI } from '@/api/submitParamsAPI.js'
export default {
  name: 'params',
  data() {
    return {
      // 级联下拉菜单数据源
      CateList: [],
      // 下拉菜单选择的数据
      selectCateKeys: [],
      // 下拉菜单的配置项
      cateListProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: 'true'
      },
      // 标签页的选中项
      activeName: 'many',
      // 动态参数的数据
      manyTableList: [],
      // 静态属性数据
      onlyTableList: [],
      // 添加参数/属性对话框显示状态
      addDialogVisible: false,
      // 添加属性/参数的表单数据
      addForm: {
        attr_name: ''
      },
      // 添加属性/参数的表单验证
      addFormrules: {
        attr_name: [
          {
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }
        ]
      },
      // 修改对话框的显示状态
      updateDialogVisible: false,
      // 修改表单输入的数据
      updateForm: {
        attr_name: ''
      },
      // 修改对话框的表单预验证
      updateFormrules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      // 文本输入框显示隐藏切换
      inputVisible: false,
      // 文本输入框输入的值
      inputValue: ''
    }
  },
  methods: {
    // 获取列表数据
    async getAllCate() {
      const { data: res } = await getAllCateListAPI()
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表失败')
      }
      this.CateList = res.data
      console.log(this.CateList)
    },
    // 监听下拉菜单的数据变化
    handleChange() {
      this.getParams()
    },
    // 监听标签页的处理函数
    handleClick() {
      console.log(this.activeName)
      this.getParams()
    },
    // 获取动态参数和静态属性
    async getParams() {
      // 如果选的不是三级分类则重置selectCateKeys数组，并退出
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyTableList = []
        this.onlyTableList = []
        return
      }
      // 如果是三级分类的话就拿到这个数组
      // console.log(this.selectCateKeys)
      const { data: res } = await getCateGoriesAPI(this.cateID, this.activeName)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableList = res.data
      } else {
        this.onlyTableList = res.data
      }
      // console.log(this.manyTableList)
      // console.log(this.onlyTableList)
    },
    // 监听对话框关闭事件的处理函数
    addFormClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击添加按钮添加属性/参数
    addParams() {
      this.$refs.addFormRef.validate(async(valid) => {
        if (!valid) return
        const { data: res } = await addParamsAPI(
          this.cateID,
          this.addForm.attr_name,
          this.activeName
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.addDialogVisible = false
        // this.$refs.addFormRef.resetFields()
        this.getParams()
      })
    },
    // 点击编辑显示修改对话框
    async showUpdateForm(attrId) {
      const { data: res } = await getUpdateCateAPI(
        this.cateID,
        attrId,
        this.activeName
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      // console.log(res)
      this.updateForm = res.data
      this.updateDialogVisible = true
    },
    // 修改对话框关闭事件处理函数
    updateFormClosed() {
      this.$refs.updateFormRef.resetFields()
    },
    // 点击确定按钮提交修改
    async updateParams() {
      const { data: res } = await updateParamsAPI(
        this.cateID,
        this.updateForm.attr_id,
        this.updateForm.attr_name,
        this.activeName
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
      this.getParams()
      this.updateDialogVisible = false
    },
    // 删除属性或参数
    async removeCate(attrId) {
      const result = await this.$confirm(
        '此操作将永久删除该内容, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // console.log(result)
      if (result !== 'confirm') {
        return this.$message.info('删除已取消')
      }
      const { data: res } = await removeCateAPI(this.cateID, attrId)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getParams()
    },
    // 监听输入框的处理函数
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveToSql(row)
    },
    // 保存数据到数据库中
    async saveToSql(row) {
      const { data: res } = await submitParamsAPI(this.cateID, row.attr_id, row.attr_name, row.attr_sel, row.attr_vals.join(' '))
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
      // this.getParams()
    },
    // 点击按钮显示文本输入框
    showInput(row) {
      row.inputVisible = true
      // $nextTick 当数据更新完毕，页面被重新渲染之后再调用$nextTick里面的回调函数内的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 标签关闭时的处理函数
    henderClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveToSql(row)
    }
  },
  created() {
    this.getAllCate()
  },
  // 计算属性，定义时采用方法的形式进行定义，使用时采用属性的形式进行使用
  computed: {
    // 控制添加按钮的禁用状态
    isBtnDisable() {
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 参数的id
    cateID() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[this.selectCateKeys.length - 1]
      }
      return null
    },
    // 对话框title显示文字
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}

.margin {
  margin: 15px 0;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 5px;
}

.input-new-tag {
  width: 120px;
}
</style>
